﻿using System;
using System.Web;
using System.IO;
using System.Data;
using MaLu.BusiLogic;
using MaLu.Common;

namespace MaluJg.web.Common
{
    public partial class GetAttach :ProjectPage
    {
        private Guid AttachmentID
        {
            get
            {
                if (Request["id"] != null)
                    return new Guid(Request["id"]);
                return Guid.Empty;
            }
        }

        private void Page_Load(object sender, System.EventArgs e)
        {


            DataTable dtAtt = BLAttach.GetAttachList(Provider, AttachmentID.ToString());

            if (dtAtt.Rows.Count>0)
            {

                showFile(dtAtt.Rows[0]["DisplayFileName"].ToString(),dtAtt.Rows[0]["PhysicalFilePath"].ToString() );
            }
            else
            {
                Response.Expires = 0;
                Response.Clear();
                Response.End();
            }
        }


        public void showFile(string name, string path)
        {
            if (System.IO.File.Exists(path))
            {
                FileStream stream = File.OpenRead(path);
                Response.Expires = 0;
                Response.Clear();
                Response.Buffer = true;
                Response.ContentType = "application/octet-stream";
                Response.AddHeader("Content-disposition", "attachment; filename=" + HttpUtility.UrlEncode(name));

                if (stream.Length > 0)
                    Response.BinaryWrite(ConvertStreamToByteBuffer(stream));
                Response.End();
            }
        }

        private byte[] ConvertStreamToByteBuffer(System.IO.Stream theStream)
        {
            if (theStream.Position > 0 && theStream.CanSeek) theStream.Position = 0;
            int b1;
            System.IO.MemoryStream tempStream = new System.IO.MemoryStream();
            while ((b1 = theStream.ReadByte()) != -1)
            {
                tempStream.WriteByte(((byte)b1));
            }
            return tempStream.ToArray();
        }
    }
}
